var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken')
const tencentcloud = require("tencentcloud-sdk-nodejs-iai")
const { userModel } = require('../model/model')
var bcryptjs = require('bcryptjs')  // 引入bcryptjs模块

const crypto = require('crypto')
const originalInput = 'mysecretpassword';
const hash = crypto.createHash('sha256');
hash.update(originalInput);
  
  router.post('/login', async (req, res) => {
    let username = req.body.username
    let password = req.body.password
    let user = await userModel.findOne({ username })
    if (!user) {
      return res.send({code:401,msg:'没有这个用户!'})
    }
    
    // 使用bcryptjs.compareSync方法进行验证,第一个参数是要验证的字符串,第二个参数是加密过的字符串
    if (!bcryptjs.compareSync(password, user.password)) {
      return res.send({code:400,msg:'密码错误!'})
    }
    res.send({code:200,msg:'登录成功!'})
  })


router.post('/zhuce', async (req, res) => {
    let body = req.body
    console.log(body);
    
    let login = await userModel.find({ username: body.username }, { password: body.password })
    if (login.length == 0) {
        await  userModel.create(body)
        res.send({
            code: 200,
        })
    } else {
        res.send({
            code: 400
        })
    }

})

router.post('/mima', async (req, res) => {
    let body = req.body
    let login = await userModel.find({ username: body.username })
    let lis = login.findIndex(item => item.username != login.username)
    if (lis) {
        res.send({
            code: 400
        })
    } else {
        await userModel.updateMany({ username: body.username }, { password: body.password })
        res.send({
            code: 200,
        })
    }
})


//人脸识别
router.post('/faceLogin', async (req, res) => {
    //获取前端传来的base64
    let b64 = req.body.b64;

    if (!b64) {
        res.send({
            code: 400,
            msg: '未接收到有效的图片数据，请重新上传图片.'
        });
        return;
    }

    const IaiClient = tencentcloud.iai.v20200303.Client;

    //用户配置
    const clientConfig = {
        credential: {
            //个人腾讯secretId
            secretId: "AKIDDHH6jBf4nMj3Vs1xhJm0FMHD0e6JSuFS",
            //个人腾讯密钥
            secretKey: "CE7wc9mFajqnnjT5XmroZBLOI0Y0KRND"
        },
        region: "ap-beijing",//地域参数（华北地区北京）
        profile: {
            httpProfile: {
                endpoint: "iai.tencentcloudapi.com",
            },
        },
    }; const client = new IaiClient(clientConfig);

    const params = {
        "GroupIds": [  //创建的人员库ID
            "zlq"
        ],
        "Image": b64,  //图片的base64格式编码
        "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
        "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
        "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
    };

    let doc = await client.SearchFaces(params)

    //doc为人脸识别后的返回信息


    if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
        let personName = doc.Results[0].Candidates[0].PersonName //拿到该人员的名称
        // console.log(personName, 'personNume');
        //生成token
        let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })

        res.send({
            code: 200,
            msg: "登录成功！",
            token
        })

    } else {
        console.log('nifdskjfklasfjsafsafsafsaf');

        res.send({
            code: 401,
            msg: '人脸库无此人！'
        })
        return false
    }

})


//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');
const { log } = require('console');

// 产生6位随机数(用来生成短信验证码的)
function getCode() {
    let str = "";
    for (let i = 0; i < 6; i++) {
        str += parseInt(Math.random() * 10)
    }
    return str;
}

// / ** 
//  *这里写post请求接口，前端调用 http://localhost:3000/api/get_sms
//  *默认端口是3000，也可以在./bin/www里面修改
//  */
router.post('/get_sms', function (req, res, next) {
    console.log(req.body);

    let phoneNum = req.body.username;  //获取前端参数phone
    console.log("手机号码", phoneNum);

    //初始化sms_client
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tGvYcwsi9seeFzW3UVY',  //accessKeyId 前面提到要准备的
        secretAccessKey: 'dXVDsN8HZWfZfTiMqvoIpu4zGWnpTm'  //secretAccessKey 前面提到要准备的
    });

    // 6位随机数
    let str = getCode();

    // 开始发送短信
    smsClient.sendSMS({
        PhoneNumbers: phoneNum,
        SignName: "璐琦佳慧", //签名名称 前面提到要准备的
        TemplateCode: "SMS_474880856", //模版CODE  前面提到要准备的
        TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
    }).then(result => {
        console.log("result", result)
        let { Code } = result;
        if (Code == 'OK') {
            res.json({
                code: 0,
                msg: 'success',
                sms: str
            })
            console.log(result)
        }
    }).catch(err => {
        console.log(err);
        res.json({
            code: 1,
            msg: 'fail: ' + err.data.Message
        })
    })

});

module.exports = router;
